package com.freewater.javabase.demo.network.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;

public class HttpClientUsage {
    public static final HttpClient httpClient = HttpClient.newBuilder().build();

    public static void main(String[] args) throws Exception {
        URI uri = new URI("https://www.liaoxuefeng.com/wiki/1252599548343744/1319099982413858");
        HttpRequest request = HttpRequest.newBuilder(uri)
                // 设置用户代理
                .header("User-Agent", "Mozilla/5.0 (compatible; MSIE 11; Windows NT 5.1)")
                // 设置可接收的内容格式
                .header("Accept", "*/*")
                // 设置超时
                .timeout(Duration.ofSeconds(5))
                // 设置版本
                .version(HttpClient.Version.HTTP_1_1)
                .build();
        final HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        // HTTP允许重复的Header，因此一个Header可对应多个Value:
        final Map<String, List<String>> headers = response.headers().map();
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue().get(0));
        }
        final String body = response.body();
        System.out.println(body.length() > 1024 ? body.substring(0, 1024) + "..." : body);
    }
}
